//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
//测试一下
// axios({
//   url: '/api/getbooks',
//   method: 'GET',
// }).then((res) => {
//   console.log(res)
// })
const tb = document.querySelector('#tb')
const form = document.querySelector('#bookForm')
const btn1 = document.querySelector('#btnAdd')
const bookname1 = document.querySelector('input[name=bookname]')
const author1 = document.querySelector('input[name=author]')
const publisher1 = document.querySelector('input[name=publisher]')
const btnSearch = document.querySelector('#btnSearch')
//渲染数据
const rendreBox = () => {
  axios({
    url: '/api/getbooks',
    method: 'GET',
  }).then(({ data: res }) => {
    const { data } = res
    tb.innerHTML = data
      .map((item) => {
        return `
                <tr>
                  <td>${item.id}</td>
                  <td>${item.bookname}</td>
                  <td>${item.author}</td>
                  <td>${item.publisher}</td>
                  <td><a href="#" data-id="${item.id}">删除</a></td>
                </tr>
              `
      })
      .join('')
  })
}
rendreBox()
//添加图书
btn1.addEventListener('click', function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  // console.log(data)
  axios({
    url: '/api/addbook',
    method: 'POST',
    data: data,
  }).then(({ data: res }) => {
    // console.log(res)
    if (res.status !== 201) return alert(res.msg)
    alert(res.msg)
    bookname1.value = ''
    author1.value = ''
    publisher1.value = ''
    rendreBox()
  })
})
//删除
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    // console.log(1)
    const id = e.target.dataset.id
    axios({
      url: '/api/delbook',
      method: 'GET',
      params: { id },
    }).then(({ data: res }) => {
      rendreBox()
    })
  }
})
//筛选数据
btnSearch.addEventListener('click', function (e) {
  e.preventDefault()
  const datas = serialize(form, { hash: true })
  const bookname = datas.bookname
  const author = datas.author
  const publisher = datas.publisher
  axios({
    url: '/api/getbooks',
    method: 'GET',
    params: {
      bookname,
      author,
      publisher,
    },
  }).then(({ data: res }) => {
    const { data } = res
    tb.innerHTML = data
      .map((item) => {
        return `
        <tr>
          <td>${item.id}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td><a href="#" data-id="${item.id}">删除</a></td>
        </tr>
      `
      })
      .join('')
  })
})
